/*
 * FilePath     : \src\utils\directives.ts
 * Author       : SJZ
 * Date         : 2025-03-12 19:28
 * LastEditors  : SJZ
 * LastEditTime : 2025-03-12 20:03
 * Description  : 自定义指令集合
 * CodeIterationRecord: 
 */

import common from "@/utils/common";
import { nextTick } from "vue";
import { ElMessage } from "element-plus";
/**
 * @description: 检核权限
 * @param el
 * @param binding
 * @return
 */

/**
 * @description: 修复表格单元格高度
 * @param el
 * @param binding
 * @return
 */
const fixCellHeight = async (el: any, binding: any) => {
  await nextTick(() => {
    const tr = el.closest(".el-table__row");
    if (!tr) {
      return;
    }
    let contentArr = Array.from(tr.getElementsByClassName(binding.value), (item) => item as Element);
    if (!contentArr?.length) {
      return;
    }
    let maxHeight = contentArr.reduce((max, td) => {
      let height: number = (td as HTMLElement).offsetHeight;
      return height > max ? height : max;
    }, 0);
    contentArr.forEach((element: Element) => {
      (element as HTMLElement).style.minHeight = `${maxHeight}px`;
    });
  });
};
/**
 * description:解决多选下拉框高度不能撑开问题
 * param {any} el
 * return {*}
 */
const fixMultipleSelectHeight = async (el: any) => {
  await nextTick(() => {
    const tagSpan = el.getElementsByClassName("el-select__tags")?.[0];
    const input = el.getElementsByClassName("el-input__inner")?.[0];
    const inputWrapper = el.getElementsByClassName("el-input--suffix")?.[0];
    if (!tagSpan || !input || !inputWrapper) {
      return;
    }
    if (tagSpan.offsetHeight === 0) {
      return;
    }
    input.style.height = tagSpan.offsetHeight + 15 + "px";
    inputWrapper.style.height = "auto";
    inputWrapper.style.setProperty("height", "auto", "important");
  });
};

//解决表格中单元格高度与同行不一致问题
const fixCellHeightDirective = {
  mounted(el: any, binding: any) {
    fixCellHeight(el, binding);
  },
  updated(el: any, binding: any) {
    fixCellHeight(el, binding);
  }
};
//解决多选下拉框高度不能撑开问题
const fixMultipleSelectHeightDirective = {
  mounted(el: any) {
    fixMultipleSelectHeight(el);
  },
  updated(el: any) {
    fixMultipleSelectHeight(el);
  }
};
/**
 * @description: dom元素点击提示信息
 */
const messageDirective = {
  beforeMount(el: HTMLElement, binding: DirectiveBinding) {
    el.addEventListener("click", () => {
      ElMessage({
        type: "info",
        center: false,
        showClose: false,
        dangerouslyUseHTMLString: true,
        customClass: "show-message",
        message: binding.value,
        grouping: true,
        offset: 300,
        duration: 2000
      });
    });
  },
  unmounted(el: HTMLElement) {
    el.removeEventListener("click", () => {});
  }
};

export default {
  install(app: any) {
    app.directive("fixCellHeight", fixCellHeightDirective);
    //解决多选下拉框高度不能撑开问题
    app.directive("fixMultipleSelectHeight", fixMultipleSelectHeightDirective);
    //message自定义指令  示例 v-message="scope.row.showMessage"
    app.directive("message", messageDirective);
  }
};
